const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const prettier = require("prettier");
const { version } = require("../package.json");

const resolvePackageJson = (relativePath) => {
    return path.resolve(__dirname, "..", relativePath, "package.json");
};

function patchVersion(packageJsons) {
    const { BUILD_NUMBER = "" } = process.env;
    const BRANCH = execSync("git rev-parse --abbrev-ref HEAD", { cwd: __dirname, encoding: "utf8" }).trim();
    const nextVersion = `${/\d+(\.\d+)*/.exec(version)[0]}-${BRANCH}${
        BUILD_NUMBER && `-${BUILD_NUMBER}`
    }`.toLowerCase();

    const packageJsonMap = new Map(
        packageJsons.map((packageJson) => {
            return [packageJson, require(packageJson)];
        })
    );

    const packageVersionMap = new Map();

    packageJsonMap.forEach((pkg) => {
        pkg.version = nextVersion;
        packageVersionMap.set(pkg.name, pkg.version);
    });

    packageJsonMap.forEach((pkg) => {
        if (pkg.dependencies) {
            Object.keys(pkg.dependencies).forEach((dep) => {
                if (packageVersionMap.has(dep)) {
                    pkg.dependencies[dep] = packageVersionMap.get(dep);
                }
            });
        }
        if (pkg.devDependencies) {
            Object.keys(pkg.devDependencies).forEach((dep) => {
                if (packageVersionMap.has(dep)) {
                    pkg.devDependencies[dep] = packageVersionMap.get(dep);
                }
            });
        }
    });

    for (let [path, content] of packageJsonMap.entries()) {
        const str = JSON.stringify(content);
        fs.writeFileSync(
            path,
            prettier.format(str, {
                parser: "json",
                printWidth: 120,
                tabWidth: 4,
                useTabs: false,
            })
        );
    }

    execSync(
        `git config --local user.email 'gitlab_as' \
          && git config --local user.name 'gitlab_as' \
          && git add ./**/package.json && git commit -m 'ci: patch version ${nextVersion}'`,
        {
            cwd: path.resolve(__dirname, ".."),
        }
    );
}

patchVersion([
    resolvePackageJson("."),
    resolvePackageJson("./applications/electron"),
    resolvePackageJson("./applications/oauth2"),
    resolvePackageJson("./applications/web"),
    resolvePackageJson("./applications/webservice"),
    resolvePackageJson("./packages/apps"),
    resolvePackageJson("./packages/common"),
    resolvePackageJson("./packages/components"),
    resolvePackageJson("./packages/microwidget"),
    resolvePackageJson("./packages/controls"),
    resolvePackageJson("./packages/icons"),
    resolvePackageJson("./packages/openapi"),
    resolvePackageJson("./packages/polyfills"),
    resolvePackageJson("./packages/webpack"),
    resolvePackageJson("./locales/anyshare-language-pack-en"),
    resolvePackageJson("./locales/anyshare-language-pack-zh-hans"),
    resolvePackageJson("./locales/anyshare-language-pack-zh-hant"),
    resolvePackageJson("./packages/sdk"),
    resolvePackageJson("./packages/sdk/public/demo"),
]);
